package study.rocketmq.usespring;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
public class ProducerService {
    private DefaultMQProducer producer = null;
    public static final String NAMESRC_ADDR = "120.25.73.46:9876";
    @PostConstruct
    public void initMQProducer() throws MQClientException {
        producer = new DefaultMQProducer("producerGroupName");
        producer.setNamesrvAddr(NAMESRC_ADDR);
        /***TODO  队列数量，默认4个 , 不建议在这里设置 ，应该先配置好topic */
        producer.setDefaultTopicQueueNums(4);
        /***TODO  超时时间，默认3秒 */
        producer.setSendMsgTimeout(3000);
        /***TODO  同步发送失败重试次数 默认就是2- 同步发送时  */
        producer.setRetryTimesWhenSendFailed(2);
        producer.start();
    }

    public SendResult send(String topic,String keys,String msg) throws Exception {
        Message message = new Message(topic,"TagA","key-1",msg.getBytes());
        SendResult sendResult =producer.send(message);
        return sendResult;
    }

    @PreDestroy
    public void showDown(){
        if(producer != null){
            producer.shutdown();
        }

    }
}

